package com.lintf.nacos.service;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.NamingEvent;

import java.io.IOException;

/**
 * @author lin tingfeng
 * @ system Mac
 * @ data 2025/3/21 11:25
 * @ package_name com.lintf.nacos.service
 * @ project_name spring-nacos
 * @ desc
 */
public class SpringNacosServiceMain1 {

    public static void main(String[] args) throws NacosException, IOException {
        NamingService namingService = NamingFactory.createNamingService("localhost:8848");
        System.out.println(namingService.getAllInstances("spring-nacos-jdk")); // 获取所有实例
        System.out.println(namingService.selectInstances("spring-nacos-jdk", true)); // 获取健康实例
        System.out.println(namingService.selectOneHealthyInstance("spring-nacos-jdk")); // 获取一个健康实例

        // 监听服务变化
        namingService.subscribe("spring-nacos-jdk", event -> {
            System.out.println(((NamingEvent) event).getServiceName() + "服务发生变化");
            System.out.println(((NamingEvent) event).getInstances() + "实例列表发生变化");
            try {
                System.out.println(namingService.getAllInstances("spring-nacos-jdk"));
            } catch (NacosException e) {
                throw new RuntimeException(e);
            }
        });

        System.in.read();
    }

}
